import { countStrToBit } from '@/utils'

export interface FileVerifyOptions {
  /* 文件类型 */
  type?: string | string[]
  /* 文件后缀 */
  suffix?: string | string[]
  /* 文件大小（单位M） */
  size?: number
  /* 文件名称长度 */
  nameLength?: number
  /* 文件名称字节长度 */
  nameByteLength?: number
}

export interface FileVerifyResult {
  code: 'success' | 'type' | 'suffix' | 'size' | 'nameLength' | 'nameByteLength'
  message: string
}

const defaultFileVerifyOptions: FileVerifyOptions = {
  type: undefined,
  suffix: undefined,
  size: undefined,
  nameLength: undefined,
  nameByteLength: undefined
}

/**
 * 文件验证
 * @param {FileVerifyOptions} options  验证配置
 */
export const useFileVerify = (options = defaultFileVerifyOptions) => {
  options = Object.assign({}, defaultFileVerifyOptions, options)

  /* 验证类型 */
  const isTypeValid = (file: File, type = options.type) => {
    if (!type) {
      return true
    }
    if (Array.isArray(type)) {
      return type.includes(file.type)
    }
    const validTypes = type?.split(',') || []
    return validTypes.includes(file.type)
  }

  /* 验证后缀 */
  const isSuffixValid = (file: File, suffix = options.suffix) => {
    if (!suffix) {
      return true
    }
    if (Array.isArray(suffix)) {
      return suffix.includes(file.name?.split('.')?.pop() || '')
    }
    const validSuffix = suffix?.split(',') || []
    return validSuffix.includes(file.name?.split('.')?.pop() || '')
  }

  /* 验证大小 */
  const isSizeValid = (file: File, size = options.size) => {
    if (!size) {
      return true
    }
    return file.size / 1024 / 1024 <= size
  }

  /* 验证名称长度 */
  const isNameLengthValid = (file: File, nameLength = options.nameLength) => {
    if (!nameLength) {
      return true
    }
    return file.name.length <= nameLength
  }

  /* 验证名称字节长度 */
  const isNameByteLengthValid = (file: File, nameByteLength = options.nameByteLength) => {
    if (!nameByteLength) {
      return true
    }
    return countStrToBit(file.name) <= nameByteLength
  }

  /* 基础验证 不满足的以FileVerifyResult形式返回 */
  const basicVerify = (file: File): FileVerifyResult => {
    if (!isTypeValid(file)) {
      return { code: 'type', message: '文件类型不合法' }
    }
    if (!isSuffixValid(file)) {
      let suffix = options?.suffix
      if (Array.isArray(suffix)) {
        suffix = suffix.join(',')
      }
      return { code: 'suffix', message: `仅支持${suffix}格式` }
    }
    if (!isSizeValid(file)) {
      return { code: 'size', message: `文件大小不能超过${options?.size}M` }
    }
    if (!isNameLengthValid(file)) {
      return { code: 'nameLength', message: `文件名不能超过${options?.nameLength}个字` }
    }
    if (!isNameByteLengthValid(file)) {
      return { code: 'nameByteLength', message: `文件名不能超过${options?.nameByteLength}个字节` }
    }

    return { code: 'success', message: '验证通过' }
  }

  return {
    basicVerify,
    isNameLengthValid,
    isNameByteLengthValid,
    isSuffixValid,
    isTypeValid,
    isSizeValid
  }
}
